package ldk.util.scrollviews

import android.content.Context
import android.support.v4.widget.NestedScrollView
import android.util.AttributeSet

/**
 * coordination with two child scrollview, has a special scrollBy
 * Created by ldkxingzhe@163.com on 2017/9/9.
 */
class NestedScrollView: NestedScrollView{
    companion object {
        val DEBUG = true
        val TAG = "NestedScrollView"
    }
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    fun scrollBy(deltaY: Int){
        val oldScrollY = scrollY
        overScrollByCompat(deltaY)
        val consumedScrollY = scrollY - oldScrollY
        val unConsumedScrollY = deltaY - consumedScrollY
        dispatchNestedScroll(0, consumedScrollY, 0, unConsumedScrollY, null)
    }

    private fun NestedScrollView.overScrollByCompat(deltaY: Int): Boolean{
        val overScrollByCompat = NestedScrollView::class.java.getDeclaredMethod("overScrollByCompat", Int::class.java, Int::class.java,
                Int::class.java, Int::class.java, Int::class.java, Int::class.java,
                Int::class.java, Int::class.java, Boolean::class.java)
        overScrollByCompat.isAccessible = true
        return overScrollByCompat.invoke(this, 0, deltaY, 0, scrollY, 0, getScrollRange(), 0, 0, false) as Boolean
    }

    // copyed from NestedScrollView

    internal fun getScrollRange(): Int {
        var scrollRange = 0
        if (childCount > 0) {
            val child = getChildAt(0)
            scrollRange = Math.max(0,
                    child.height - (height - paddingBottom - paddingTop))
        }
        return scrollRange
    }
}